package com.fms.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fms.result.ResultData;
import com.fms.dto.DeptAccess;
import com.fms.mapper.MenuCheckMapper;
import com.fms.mapper.MenuMapper;
import com.fms.mapper.SysDeptMapper;
import com.fms.entity.Menu;
import com.fms.entity.MenuCheck;
import com.fms.entity.SysDept;
import com.fms.service.MenuCheckService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/permission")
@RequiredArgsConstructor
public class PermissionController {

    private final MenuCheckService menuCheckService;

    private final SysDeptMapper sysDeptMapper;

    private final MenuCheckMapper menuCheckMapper;

    private final MenuMapper menuMapper;

    //获取部门与权限内容
    @GetMapping("/getPermission")
    public ResultData getPermission(){
        List<DeptAccess> permissionList = getPermissionList();
        return ResultData.success(permissionList);
    }

    //更新权限
    @PostMapping("/changePermission")
    public ResultData changePermission(@RequestBody DeptAccess deptAccess){
        String message = menuCheckService.updateAccess(deptAccess);
        return ResultData.success(message);
    }

    public List<DeptAccess> getPermissionList(){
        List<DeptAccess> list = new ArrayList<>();
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        List<SysDept> sysDepts = sysDeptMapper.selectList(queryWrapper);
        //部门内容
        for (SysDept sysDept:sysDepts){
            DeptAccess deptAccess = new DeptAccess();
            deptAccess.setId(sysDept.getId());
            deptAccess.setDeptName(sysDept.getName());

            Long deptId = sysDept.getId();
            LambdaQueryWrapper<MenuCheck> menuCheckLambdaQueryWrapper = new LambdaQueryWrapper<>();
            menuCheckLambdaQueryWrapper.eq(MenuCheck::getDeptId, deptId);

            List<MenuCheck> menuChecks = menuCheckMapper.selectList(menuCheckLambdaQueryWrapper);
            List<Menu> menus = new ArrayList<>();
            List<Long> menuIds = new ArrayList<>();

            //插入对应权限
            for (MenuCheck check : menuChecks){
                Long menuId = check.getMenuId();
                menuIds.add(menuId);
                LambdaQueryWrapper<Menu> menuLambdaQueryWrapper = new LambdaQueryWrapper<>();
                menuLambdaQueryWrapper.eq(Menu::getId, menuId);
                //menuLambdaQueryWrapper.ne(Menu::getStatus, 0);
                Menu menu = menuMapper.selectOne(menuLambdaQueryWrapper);
                menus.add(menu);
            }
            deptAccess.setMenuIds(menuIds);
            deptAccess.setMenus(menus);
            list.add(deptAccess);
        }
        return list;
    }
}
